package com.livepan.server.utils;

import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.sms.v20190711.SmsClient;
import com.tencentcloudapi.sms.v20190711.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20190711.models.SendSmsResponse;
import com.tencentcloudapi.sms.v20190711.models.SendStatus;
import com.livepan.server.error.BusinessException;
import com.livepan.server.error.EmBusinessError;

/**
 * 发送验证码的工具
 */
public class SendSms {


    public static boolean send(String telephone, String code) throws BusinessException {
        return send(telephone, code, 86);
    }

    /**
     * 发送验证码
     *
     * @param telephone 电话号码
     * @param code      验证码
     * @param pre       地区前缀
     * @return 是否发送成功
     */
    public static boolean send(String telephone, String code, int pre) throws BusinessException {
        try {

            Credential cred = new Credential(ConstUtil.secretId, ConstUtil.secretKey);

            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("sms.tencentcloudapi.com");

            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);

            SmsClient client = new SmsClient(cred, "ap-guangzhou", clientProfile);

            //添加地区前缀
            telephone = pre + telephone;
            String params = "{\"PhoneNumberSet\":[" + telephone + "],\"TemplateID\":\"565338\",\"Sign\":\"玄奇网\",\"TemplateParamSet\":[" + code + "],\"SmsSdkAppid\":\"1400340950\"}";
            SendSmsRequest req = SendSmsRequest.fromJsonString(params, SendSmsRequest.class);

            SendSmsResponse resp = client.SendSms(req);

            System.out.println(SendSmsRequest.toJsonString(resp));

            //唯一请求 ID，每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
            String requesdId = resp.getRequestId();

            SendStatus[] sendStatusSet = resp.getSendStatusSet();

            //只有发送成功了才会返回true
            for (SendStatus sendStatus : sendStatusSet) {
                if ("Ok".equals(sendStatus.getCode())) {
                    return true;
                } else {
                    throw new BusinessException(EmBusinessError.OTPCODE_SEND_ERROR, sendStatus.getMessage());
                }
            }
            return false;
        } catch (TencentCloudSDKException e) {
            System.out.println(e.toString());
            return false;
        }
    }
}
